package com.atguigu.gulimall.ssoclient.cotroller;

import com.sun.deploy.net.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 马迎迎
 * @Title: HelloController
 * @Package com.atguigu.gulimall.ssoclient.cotroller
 * @Description: TODO(添加描述)
 * @date 2021年05月27日 15:44
 */
@Controller
public class HelloController {

    @Value("${sso.server.url}")
    String ssoServerUrl;
    /**
     * 无需登录就可访问
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }

    /**
     * 感知这次是在ssoserver登录成功返回来的
     * @param model
     * @param session
     * @return
     */
    @GetMapping("/employees")
    public String employees(@RequestParam(value = "token",required = false) String token, Model model, HttpSession session){
        if(!StringUtils.isEmpty(token)){
            //登录成功后带上的
            //TODO 去ssoserver获取当前token真正对应的用户信息
            RestTemplate restTemplate=new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://ssoserver.com:8080/useInfo?token=" + token, String.class);
            String body = forEntity.getBody();
            session.setAttribute("loginUser",body);
        }
        Object loginUser = session.getAttribute("loginUser");
        if(loginUser==null){
            //没登录 跳转到登录服务器登录
            //redirect_url=告诉认证服务器自己原页面是什么
            return "redirect:"+ssoServerUrl+"?redirect_url=http://client1.com:8082/employees";
        }else{
            //登录了
            List<String> list=new ArrayList<>();
            list.add("张三");
            list.add("李四");
            model.addAttribute("emps",list);

            return "list";
        }

    }
}
